﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiveCharts.Wpf.Messager
{
    public class Messager
    {
        /// <summary>
        /// 消息集合
        /// </summary>
        private IDictionary<string, MessagerInvokeHandler> Messagers =
            new Dictionary<string, MessagerInvokeHandler>();

        private Messager() { }

        private static Messager _message;

        public static Messager Default => _message ?? (_message = new Messager());

        /// <summary>
        /// 订阅
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="topic"></param>
        /// <param name="t"></param>
        public virtual void Register<T>(string topic, Action<MessagerContext> t)
        {
            if (t == null)
                throw new ArgumentException();
            if (Messagers.ContainsKey(topic))
            {
                var value = Messagers.FirstOrDefault(o => o.Key == topic).Value;
                value.MessagerInvokeEvent += t;
                return;
            }
            var invoker = new MessagerInvokeHandler();
            invoker.MessagerInvokeEvent += t;
            Messagers.Add(topic, invoker);
        }

        /// <summary>
        /// 发布
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="topic"></param>
        /// <param name="element"></param>
        public virtual void Send<T>(string topic, T element)
        {
            if (!Messagers.ContainsKey(topic))
                return;
            var invoker = Messagers.FirstOrDefault(o => o.Key == topic).Value;
            invoker.Invoke(new MessagerContext()
            {
                Data = element,
                Topic = topic
            });
        }
    }
}
